#-*- coding:utf-8 -*-

from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.template import Context, RequestContext
from django.shortcuts import render_to_response
from django.template.loader import get_template
from django.contrib.auth.models import User
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required

from record.forms import *
from record.models import *

import math
import xml_util
import datetime

import logging
log = logging.getLogger(__name__)


timetable = {'01':1, '02':1,
        '03':2, '04':2,
        '05':3, '06':3,
        '07':4, '08':4,
        '09':5, '10':5,
        '11':6, '12':6,
        '13':7, '14':7,
        '15':8, '16':8,
        '17':9, '18':9,
        '19':10, '20':10,
        '21':11, '22':11,
        '23':12, '24':12}



def testpage(request):

    obj = Account.objects.get(pk=1)
    #print obj.use_yn, obj.acct_name
    #data = {'acct_code':'TEST', 'acct_name':'개복치'}
    form = TestForm(instance=obj)


    variables = RequestContext(request , {'form':form})

    return render_to_response('record/test.html', variables)


def account_create_page(request):

    if request.method == 'POST':
        form = AccountForm(request.POST)
        if form.is_valid():

            print dir(form)

            account = Account(account_code=form.cleaned_data['account_code'],
                    account_name=form.cleaned_data['account_name'])

            account.save()

            return HttpResponseRedirect('/register/success/')
    else:
        form = AccountForm()

    variables = RequestContext(request, {'form':form})

    return render_to_response('account/create.html', variables)


def account_edit_page(request):
    form = AccountForm()

    variables = RequestContext(request , {'form':form})

    return render_to_response('record/test.html', variables)






def user_logout(request):
    logout(request)
    return HttpResponseRedirect('/')








def register_page(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                    username = form.cleaned_data['username'],
                    password = form.cleaned_data['password1'],
                    email = form.cleaned_data['email']
                    )
            return HttpResponseRedirect('/register/success/')
    else:
        form = RegistrationForm()

    variables = RequestContext(request, {'form':form})

    return render_to_response('registration/register.html', variables)



def last_day_of_month(date):
    if date.month == 12:
        return date.replace(day=31)
    return date.replace(month=date.month+1, day=1) - datetime.timedelta(days=1)


def current_duration(duration=None):

    if duration is not None:
        log.info("@@@")
        year = duration[:4]
        dur = duration[4:]

        start = datetime.date(int(year), int(timetable[dur]), 16 if int(dur) % 2 < 1 else 1)
        end = last_day_of_month(start) if int(dur) % 2 < 1 else datetime.date(int(year), int(timetable[dur]), 15)
    else:
        now = datetime.date.today()
        if now.day < 16:
            start = datetime.date(now.year, now.month, 1)
            end = datetime.date(now.year, now.month, 15)

            mon = str(now.month * 2 - 1)
            if len(mon) < 2:
                mon = '0' + mon

            duration = str(now.year) + mon

        else:
            start = datetime.date(now.year, now.month, 16)
            end = last_day_of_month(start)

            mon = str(now.month * 2)
            if len(mon) < 2:
                mon = '0' + mon

            duration = str(now.year) + mon

        log.info("^^^^^^^^^^ = " + duration)


    return {'duration':duration, 'start':start, 'end':end}

def previous_duration(duration):
    year = duration[:4]
    dur = duration[4:]

    if int(dur) - 1 < 1:
        year = str(int(year) - 1)
        dur = '24'

        duration = year + dur
    else:

        if len(str(int(dur) - 1)) < 2:
            dur = '0' + str(int(dur) - 1)
        else:
            dur = str(int(dur) - 1)

        duration = year + dur

    return duration

def next_duration(duration):
    year = duration[:4]
    dur = duration[4:]

    if int(dur) + 1 > 24:
        year = str(int(year) + 1)
        dur = '01'

        duration = year + dur
    else:

        if len(str(int(dur) + 1)) > 2:
            dur = '0' + str(int(dur) +1)
        else:
            dur = str(int(dur) +1)

        duration = year + dur

    return duration


@login_required(redirect_field_name='redirect_to')
def sheet_page(request, duration=None):
    '''Main work sheet page'''
    
    profile = request.session['profile']
    house_code = request.session.get('profile').dept.company.group.house_code
    log.info("house_code = " + house_code)

    start, end = None, None
    diff_days = list()
    diff_day_count = 0

    dur = current_duration(duration)
    #dur = current_duration('201001')

    duration = dur['duration']
    start = dur['start']
    end = dur['end']

    previous_period = previous_duration(duration)
    next_period = next_duration(duration)


    log.info("start = " + str(start))
    log.info("end = " + str(end))


    cursor_date = start
    while cursor_date <= end:
        diff_days.append(cursor_date)
        cursor_date = cursor_date + datetime.timedelta(days=1)
        diff_day_count += 1
        print cursor_date






    variables = RequestContext(request,	{
        'current_duration':duration,
        'previous_duration':previous_period,
        'next_duration':next_period,
        'start':start,
        'end':end,
        'diff_days':diff_days,
        'korea':'team'
        })

    return render_to_response('record/sheet.html', variables)





















class FooUrl(object):

    def __init__(self):
        self.logger = None


    def foo(self, request):
        return render_to_response('main_page.html', RequestContext(request))


    def account_edit_page(self, request, account_code=None):

        account = Account.objects.get(account_code=account_code)

        form = AccountForm(instance=account)

        variables = RequestContext(request, {
            'form':form
            })

        return render_to_response('account/edit.html', variables)


    def account_list_page(self, request):
        '''
        계정 코드 리스트 페이지
        '''
        print '%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'
        print '%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'

        if request.method == 'GET':

            self.logger.debug('get request!')
            account = Account.objects.all()
            variables = RequestContext(request, {
                'account':account
                })
            return render_to_response('account/list.html', variables)




        if request.is_ajax() == True:
            self.logger.debug('ajax request!')
            self.logger.debug('### %s' % (request.POST['flag']))

            page = int(request.POST['page']) # client-side : 현재페이지
            limit = int(request.POST['rows']) # client-side : 화면에 보여지는 갯수
            count = 0 # (전체 모델 카운트)
            total_page = 0 # 전체 페이지 수
            start = 0 # 시작 번호

            account = Account.objects.order_by('account_code').all()
            #account = Account.objects.filter(acct_code='099995').order_by('acct_code').all()
            #account = Account.objects.filter(acct_code__gt = '098990').filter(acct_code__lt='098994').order_by('acct_code').all()


            count = len(account)
            if count > 0:
                total_page = count / limit
                if count % limit > 0:
                    total_page = total_page + 1
            else:
                total_page = 0


            if page > total_page :
                page = total_page

            start = limit * page - limit


            self.logger.info('@@@@@@@@@@@@@@@@@@@@@')
            self.logger.info('page = %d' % page)
            self.logger.info('limit = %s' % limit)
            self.logger.info('start = %d' % start)
            self.logger.info('total_page = %d' % total_page)
            self.logger.info('@@@@@@@@@@@@@@@@@@@@@')



            if total_page == page:
                account = Account.objects.order_by('account_code').all()[start:] #마지막일 경우에는 끝가지
            else:
                account = Account.objects.order_by('account_code').all()[start:(start + limit)]

            xutil = xml_util.XmlCreator()
            xml = xutil.createXml(account, page, total_page)

            #xml = xml.createXml(account, page, total_page)

            return HttpResponse(xml, mimetype='text/xml; charset=utf-8')
